import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.List;

public class JavaToMyBatis {
    SqlSession session;

    public void beforeLoadXML(){
        //加载 mybatis 配置文件
        InputStream inputStream = JavaToMyBatis.class.
                getClassLoader().getResourceAsStream("mybatis-config.xml");
        //构建sqlSession的工厂
        SqlSessionFactory sqlSessionFactory =
                new SqlSessionFactoryBuilder().build(inputStream);
        //根据 sqlSessionFactory 产生 session
        session = sqlSessionFactory.openSession();
    }

   //根据id查询
    public void testSelectById(int id){
        //这个字符串有 personMapper.xml 文件中 两个部分构成
        //<mapper namespace="com.ys.bean.personMapper"> 的 namespace 的值
        //<select id="selectPersonById" > id 值
        String statement = "studentMapper"+".selectStudentById";
        Student p = session.selectOne(statement,id);
        System.out.println(p);
        session.close();
    }

    //查询整表
    public List<Student> getAllInTable(){
        String statement = "studentMapper"+".getAllInTable";
        List<Student> tb_student = session.selectList(statement);
        session.close();  //此处每执行了一条sql语句就会关闭会话，会不会很麻烦？
        return tb_student;
    }

    //插入表信息
    public void insertInfo(Student ele_student){
        String statement = "studentMapper"+".insertInfo";
        session.insert(statement,ele_student);
        session.commit();
        session.close();
    }

    public void deleteInfoById(int id){
        String statement = "studentMapper"+".deleteInfoById";
        session.delete(statement,id);
        session.commit();
        session.close();
    }
}
